package com.awei.study.dataStructure.queue;

import com.awei.study.dataStructure.queue.abs.Priority;
import com.awei.study.dataStructure.queue.abs.Queue;

import java.util.Iterator;

/**
 * @Author liweilong
 * @Date 2023/5/25 11:21
 */
public class Priority_Queue_DisOrder<E extends Priority> implements Queue<E>,Iterable<E> {

    Priority[] array;

    int size = 0;

    public Priority_Queue_DisOrder(int capacity) {
        array = new Priority[capacity];
    }

    @Override
    public boolean offer(E value) {
        if(isFull()) return false;
        array[size] = value;
        size++;
        return false;
    }

    @Override
    public E poll() {
        if(isEmpty()) return null;
        int max = selectMax();
        E p = (E) array[max];
        remove(max);
        return p;
    }

    private void remove(int index) {
        if(index != size - 1) {
            System.arraycopy(array,index + 1 ,array,index,size - 1 - index);
        }
        size--;
        array[size] = null;
    }

    private int selectMax() {
        int max = 0;
        for (int i = 1; i < size; i++) {
            if(array[i].priority() > array[max].priority()) {
                max = i;
            }
        }
        return max;
    }

    @Override
    public E peek() {
        if(isEmpty()) return null;
        int max = selectMax();
        E p = (E) array[max];
        return p;
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = 0;
            @Override
            public boolean hasNext() {
                return p != size;
            }

            @Override
            public E next() {
                E value = (E) array[p];
                p++;
                return value;
            }
        };
    }
}
